import config from '@/utils/config.js'

export default {
	state: {
		socket: null,
	},
	mutations: {
		SET_SOCKET: (state, data) => {
			state.socket = data
		}
	},
	actions: {
		connectSocket: (store, id) => {
			let socketTask = uni.$store.get('socketTask')
			const { commit } = store
			if(socketTask.close == undefined) {
				socketTask = uni.connectSocket({
					url: config.socket + '/socket/' + id,
					complete: () => {}
				})
			}
			socketTask.onOpen(() => {
				console.log('socket连接成功');
				commit('SET_SOCKET', socketTask)
				uni.$store.set('socketTask', socketTask)
			})
			socketTask.onClose(() => {
				console.log('socket断开连接');
				store.commit('SET_SOCKET', null)
			})
		},
		closeSocket: (store) => {
			const socketTask = uni.$store.get('socketTask')
			if(socketTask) {
				socketTask.close()
			}
			store.commit('SET_SOCKET', null)
		}
	}
}